package grpc

import (
	"context"
	logv1 "gitee.com/xiao_hange/go-admin-api/api/proto/gen/log/v1"
	"gitee.com/xiao_hange/go-admin-log/log/domain"
	"gitee.com/xiao_hange/go-admin-log/log/service"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc"
)

type LogServiceServer struct {
	logv1.UnimplementedLogServiceServer
	tracer trace.Tracer
	scv    service.LogService
}

func NewLogServiceServer(scv service.LogService) *LogServiceServer {
	return &LogServiceServer{
		scv:    scv,
		tracer: otel.Tracer("Log服务-GRPC层"),
	}
}

func (f *LogServiceServer) Register(server *grpc.Server) {
	logv1.RegisterLogServiceServer(server, f)
}

func (f *LogServiceServer) InputLog(ctx context.Context, req *logv1.InputLogRequest) (*logv1.InputLogResponse, error) {
	err := f.scv.InsertDocument(ctx, req.Index, req.Message)
	if err != nil {
		return nil, err
	}
	return &logv1.InputLogResponse{}, nil
}
func (f *LogServiceServer) SearchLog(ctx context.Context, req *logv1.SearchLogRequest) (*logv1.SearchLogResponse, error) {
	datas, total, err := f.scv.SearchLog(ctx, req.Index, int(req.Page), int(req.Limit))
	if err != nil {
		return nil, err
	}
	result := make([]*logv1.Data, len(datas))
	for i, v := range datas {
		result[i] = f.toDTOData(v)
	}
	return &logv1.SearchLogResponse{
		Data: result,
		Nt:   int64(total),
	}, nil
}
func (f *LogServiceServer) toDTOData(fi domain.Log) *logv1.Data {
	return &logv1.Data{
		Message: fi.Message,
	}
}
